import 'dart:convert';
import 'dart:ui';

import 'package:dio/dio.dart';

import '../entity/TextMessage.dart';

class EventStreamManager {
  static Future<void> send(String url, Map<String, dynamic> params,
      Function(TextMessage message) callback,VoidCallback onDone) async {
    try {
      final dio = Dio();
      final formData = FormData.fromMap(params);
      Response<ResponseBody> response = await dio.post<ResponseBody>(
        url,
        data: formData,
        options: Options(
          responseType: ResponseType.stream,
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        ),
      );
      final stream = response.data?.stream;
      if (stream != null) {
        stream.listen(
          (List<int> chunk) {
            final decodedResponse = utf8.decode(chunk);
            Map<String, dynamic> jsonMap = jsonDecode(decodedResponse);
            TextMessage message = TextMessage.fromJson(jsonMap);
            callback(message);
          },
          onError: (error) {
            print("111111111111:${response.data}");
            print('Stream error: $error');
          },
          onDone: () {
            onDone();
          },
        );
      }
    } catch (e) {
      print('Request failed: $e');
    }
  }
}
